<template>
    <div class="admin-container">
      <el-card class="search-card">
        <el-form :inline="true" :model="searchForm" class="search-form">
          <el-form-item label="设备名称">
            <el-input v-model="searchForm.deviceName" placeholder="请输入设备名称"></el-input>
          </el-form-item>
          <el-form-item label="员工">
            <el-select 
              v-model="searchForm.employeeId" 
              placeholder="请选择员工"
              filterable
              clearable
            >
              <el-option
                v-for="emp in employeeList"
                :key="emp.jobNumber"
                :label="emp.name"
                :value="emp.jobNumber"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="时间范围">
            <el-date-picker
              v-model="searchForm.timeRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY/MM/DD"
              value-format="YYYY-MM-DD"
            ></el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>
  
      <el-card class="table-card">
        <div class="table-header">
          <span>巡检记录</span>
          <el-button 
            type="danger" 
            :disabled="multipleSelection.length === 0"
            @click="handleBatchDelete"
          >
            批量删除
          </el-button>
        </div>
  
        <el-table
          :data="inspectionList"
          style="width: 100%"
          v-loading="loading"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="30"></el-table-column>
          <el-table-column prop="deviceId" label="设备ID" width="70"></el-table-column>
          <el-table-column prop="deviceName" label="设备名称" width="100"></el-table-column>
          <el-table-column label="温度(℃)" width="150">
            <template #default="{row}">
              <span :class="{'warning-text': !isTempNormal(row)}">
                {{ row.temperature }} / {{ row.temperatureRange }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="电压(V)" width="150">
            <template #default="{row}">
              <span :class="{'warning-text': !isVoltageNormal(row)}">
                {{ row.voltage }} / {{ row.voltageRange }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="description" label="描述" show-overflow-tooltip></el-table-column>
          <el-table-column prop="employeeName" label="巡检者" width="100"></el-table-column>
          <el-table-column prop="createTime" label="创建时间" width="180"></el-table-column>
          <el-table-column label="操作" width="180" fixed="right">
            <template #default="{row}">
              <el-button size="small" @click="showImages(row)">查看图片</el-button>
              <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
  
        <div class="pagination-container">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="pagination.current"
            :page-sizes="[10, 20, 30, 50]"
            :page-size="pagination.size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="pagination.total"
          ></el-pagination>
        </div>
      </el-card>
  
      <!-- 图片查看对话框 -->
      <el-dialog v-model="showImageDialog" title="巡检图片" width="60%">
      <div class="image-preview-container" v-if="currentImages.length > 0">
        <el-image 
          v-for="(img, index) in currentImages" 
          :key="index"
          :src="img.url" 
          :preview-src-list="currentImages.map(i => i.url)"
          fit="contain"
          style="width: 100%; height: 400px; margin-bottom: 10px;"
          hide-on-click-modal
        ></el-image>
      </div>
      <el-empty description="暂无图片" v-else></el-empty>
    </el-dialog>
    </div>
  </template>
  
  <script lang="ts" setup>
  import { ref, reactive, onMounted } from 'vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import { 
    getInspectionRecords,
    deleteInspectionRecord,
    batchDeleteInspectionRecords,
    getImage
  } from '@/api/inspection'
  import { getEmployeeList } from '@/api/device'
  // 搜索表单
  const searchForm = reactive({
    deviceName: '',
    employeeId: '',
    timeRange: []
  })
  
  // 分页
  const pagination = reactive({
    current: 1,
    size: 10,
    total: 0
  })
  
  const inspectionList = ref([])
  const loading = ref(false)
  const employeeList = ref([])
  const multipleSelection = ref([])
  const showImageDialog = ref(false)
  const currentImages = ref([])
  
  // 获取员工列表
  const fetchEmployeeList = async () => {
    try {
      const res = await getEmployeeList()
      employeeList.value = res.data
    } catch (error) {
      ElMessage.error('获取员工列表失败')
    }
  }
  
  // 获取巡检记录
  const fetchInspectionRecords = async () => {
    try {
      loading.value = true
      const params = {
        pageNum: pagination.current,
        pageSize: pagination.size,
        deviceName: searchForm.deviceName,
        employeeId: searchForm.employeeId,
        startTime: searchForm.timeRange?.[0],
        endTime: searchForm.timeRange?.[1]
      }
      console.log(searchForm.timeRange)
      console.log()
      const res = await getInspectionRecords(params)
      inspectionList.value = res.data.records
      pagination.total = res.data.total
    } catch (error) {
      ElMessage.error('获取巡检记录失败')
    } finally {
      loading.value = false
    }
  }
  
  // 检查温度是否正常
  const isTempNormal = (row : any) => {
    const { temperatureRange, temperature } = row
    const lower = temperatureRange - 5
    const upper = temperatureRange + 5
    return temperature >= lower && temperature <= upper
  }
  
  // 检查电压是否正常
  const isVoltageNormal = (row : any) => {
    const { voltageRange, voltage } = row
    const lower = voltageRange * 0.9
    const upper = voltageRange * 1.1
    return voltage >= lower && voltage <= upper
  }
  
  const showImages = (row: any) => {
  getImage(row.id).then(res => {
    currentImages.value = res.data.map((img :any) => {
      return {
        id: img.id,
        url: img.url  // 直接使用后端返回的图片URL
      }
    })
  })
  showImageDialog.value = true
}
  
  // 删除记录
  const handleDelete = (row : any) => {
    ElMessageBox.confirm('确定要删除这条巡检记录吗?', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(async () => {
      try {
        await deleteInspectionRecord(row.id)
        ElMessage.success('删除成功')
        fetchInspectionRecords()
      } catch (error) {
        ElMessage.error('删除失败')
      }
    }).catch(() => {})
  }
  
  // 批量删除
  const handleBatchDelete = () => {
    if (multipleSelection.value.length === 0) return
    
    ElMessageBox.confirm(`确定要删除选中的${multipleSelection.value.length}条记录吗?`, '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(async () => {
      try {
        const ids = multipleSelection.value.map(item => item.id)
        await batchDeleteInspectionRecords(ids)
        ElMessage.success(`成功删除${ids.length}条记录`)
        fetchInspectionRecords()
        multipleSelection.value = []
      } catch (error) {
        ElMessage.error('批量删除失败')
      }
    }).catch(() => {})
  }
  
  // 表格选择变化
  const handleSelectionChange = (val:any) => {
    multipleSelection.value = val
  }
  
  // 搜索
  const handleSearch = () => {
    pagination.current = 1
    fetchInspectionRecords()
  }
  
  // 重置搜索
  const resetSearch = () => {
    searchForm.deviceName = ''
    searchForm.employeeId = ''
    searchForm.timeRange = []
    pagination.current = 1
    fetchInspectionRecords()
  }
  
  // 分页
  const handleSizeChange = (val:any) => {
    pagination.size = val
    fetchInspectionRecords()
  }
  
  const handleCurrentChange = (val:any) => {
    pagination.current = val
    fetchInspectionRecords()
  }
  
  onMounted(() => {
    fetchEmployeeList()
    fetchInspectionRecords()
  })
  </script>
  
  <style scoped>
  .admin-container {
    padding: 20px;
  }
  
  .search-card {
    margin-bottom: 20px;
  }
  
  .table-card {
    margin-bottom: 20px;
  }
  
  .table-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
  }
  
  .warning-text {
    color: #e6a23c;
    font-weight: bold;
  }
  
  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
  .image-preview-container {
  display: flex;
  flex-direction:row;
  align-items: center;
}
.image-gallery {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  justify-content: flex-start;
}

  </style>